<script setup>
import { reactive, ref } from 'vue';
import { changePage } from '../tools/linkTo';

// ================== Constants ==================
const BLOKS = {
    AIR: 0,
    SPAWN: 1,
    STAR: 2,
    BASE: 3,
    SPRING: 4,
    SLOPE: 5,
    MOVE: 6,
}

// ================== State ==================
/**
 * @typedef {0|1|2|3|4|5|6} BlokType // BLOKS values
 */
/** @type {BlokType[][][]} 3 maps, each 10x20 grid */
const mapData = reactive(
    JSON.parse(localStorage.getItem('mapdata')) || 
    Array.from({ length: 3 }, () =>
        Array.from({ length: 12 }, () =>
            Array.from({ length: 20 }, () => BLOKS.AIR)
        )
    )
);

// Current level and positioning
const index = ref(0);
const x = ref(0);
const y = ref(30);

// Level completion status
const isPass = [0, 0, 0];

// Current selected tool
const currentTool = ref(BLOKS.SPAWN);

// Tool list
const toolList = [
    { type: BLOKS.SPAWN, icon: '🚩', label: 'Spawn Point' },
    { type: BLOKS.STAR, icon: '✨', label: 'Star' },
    { type: BLOKS.BASE, icon: '🟦', label: 'Base Blocks' },
    { type: BLOKS.SPRING, icon: '🦘', label: 'Jump Spring' },
    { type: BLOKS.SLOPE, icon: '🔺', label: 'Sloped Blocks' },
    { type: BLOKS.MOVE, icon: '↔️', label: 'Moving Platform' },
    { type: BLOKS.AIR, icon: '', label: 'Remove' },
];

// ================== Methods ==================

/**
 * Select a tool for map editing
 * @param {BlokType} type - Block type to select
 */
function selectTool(type) {
    currentTool.value = type;
}

/**
 * Count blocks of specific type in current map
 * @param {BlokType} type - Block type to count
 * @returns {number} - Count of blocks
 */
function countType(type) {
    return mapData[index.value].flat().filter(i => i === type).length;
}

/**
 * Save map to localStorage
 */
function saveMap() {
    localStorage.setItem('mapdata', JSON.stringify(mapData));
}

/**
 * Change block type at specified position
 * @param {number} x - X coordinate
 * @param {number} y - Y coordinate
 * @param {BlokType} type - New block type
 */
function changeItem(x, y, type) {
    // Validate placement constraints
    if ((type === BLOKS.SPAWN && countType(BLOKS.SPAWN) >= 1) ||
            (type === BLOKS.STAR && countType(BLOKS.STAR) >= 3)) {
        alert(type === BLOKS.SPAWN ? 'Only one spawn point allowed' : 'Maximum 3 stars allowed');
        return;
    }
    
    mapData[index.value][x][y] = type;
    saveMap();
}

/**
 * Export map as downloadable JSON file
 */
function exportMap() {
    const data = localStorage.getItem("mapdata");
    const blob = new Blob([data], {type: "application/json"});
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "地图.json";
    a.click();
}

/**
 * Go to Play page
 */
function toPlay(){
    localStorage.setItem("level",index.value)
    changePage('Game')
}

// ================== Event Handlers ==================
window.addEventListener("keydown", (k) => {
    if (k.key === "r" || k.key === "R") {
        x.value += 100;
    } else if (k.key === "y" || k.key === "Y") {
        x.value -= 100;
    }
});
</script>

<template>
    <div class="page">
        <!-- 工具 -->
        <div class="l">
            <h2>Tools Box</h2>
            <div class="tools">
                <div
                    v-for="tool in toolList"
                    :key="tool.type"
                    :class="currentTool == tool.type ? 'choose' : ''"
                    @click="selectTool(tool.type)"
                >
                    {{ tool.icon }}{{ tool.label }}
                </div>
            </div>
        </div>

        <!-- 地图编辑 -->
        <div class="c">

            <!-- 编辑界面 for循环出dom -->
            <div class="edit" :style="{ left: x + 'px', bottom: y + 'px' }">
                <div class="itemX" v-for="(row, Xindex) in mapData[index]" :key="Xindex">
                    <div 
                    v-for="(cell, Yindex) in row" 
                    class="itemY" 
                    :class="`blok-${cell}`" 
                    :key="Yindex" 
                    @click="changeItem(Xindex, Yindex, currentTool)
                    ">
                    </div>
                </div>
            </div>

        </div>

        <!-- 其他操作 -->
        <div class="r">
            <div class="play" @click="toPlay()">Play Demo</div>
            <div class="levels" style="flex-grow: 1;">
                <button @click="index = 0">Level 1</button>
                <button @click="index = 1">Level 2</button>
                <button @click="index = 2">Level 3</button>
            </div>
            <div class="fun">
                <div @click="changePage()">Home</div>
                <div>Load</div>
                <div @click="exportMap()">Export</div>
            </div>
        </div>
    </div>
    <div v-if="false">
        Game
    </div>
</template>

<style scoped>
.page {
    display: flex;
    height: 100vh;
}

.page .l{
    width: 260px;
}
.page .r {
    width: 180px;
}

.page .l .tools div {
    padding: 8px 40px;
    cursor: pointer;
}

.tools .choose {
    color: rgb(255, 178, 178);
}

.page .r {
    display: flex;
    flex-direction: column;
}
.page .r .play {
    text-align: center;
    cursor: pointer;
    padding: 20px;
    border-bottom: 1px solid #888;
    transition: all 0.2s;
}
.page .r .play:hover {
    color: aqua;
}
.page .r .levels {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 15px 50px;
}
.page .r .levels button{
    background-color: #fdfeff;
    border: 1px solid rgb(125, 181, 255);
    border-radius: 4px;
    padding: 8px;
    transition: all 0.5s;
}
.page .r .levels button:hover{
    background-color: #d1e8ff;
}

.page .r .fun div {
    padding: 14px;
    text-align: center;
    border-top: 1px solid #e7e7e7;
}

.page .r .fun div:hover {
    background-color: #f3f3f3;
    cursor: pointer;
}

.page .c {
    flex-grow: 1;
    border-left: 1px solid #ededed;
    border-right: 1px solid #ededed;
    overflow: hidden;
    background-color: #e7e7e7;
}

.page .c .edit {
    position: absolute;
    transition: all .5s;
    border: 1px solid #cfcfcf;
    box-shadow: rgb(175, 255, 197) 0px 0px 8px;
}

h2 {
    text-align: center;
}

.c {
    position: relative;
}

.c .itemX {
    display: flex;
}

.itemY {
    display: block;
    width: 75px;
    height: 75px;
    background-color: white;
}

.itemY:hover {
    animation: donghua 1s infinite;
}

@keyframes donghua {
    0% {
        background-color: white;
    }

    50% {
        background-color: rgb(204, 204, 204);
    }

    100% {
        background-color: white;
    }
}

.blok-0 {
    background-color: white;
}

.blok-1::after {
    content: "🚩";
}

.blok-2::after {
    content: "✨";
}

.blok-3 {
    background-color: #3da9fc;
}

/* Base Block 蓝色 */
.blok-4::after {
    content: "🦘";
}

.blok-5::after {
    content: "🔺";
}

.blok-6::after {
    content: "↔️";
}
</style>
